﻿using System;
using System.Collections.Generic;
using TeamTasker.Utils;

namespace TeamTasker.Server.DataAccess.Support
{
    public class DictionaryRegistry
    {
        public string[] DictNames { get; set; }
        
        private Dictionary<string, Dictionary> dictionaries = null;
        public DictionaryDAO Dao { get; set; }

        public void Init()
        {
            if (dictionaries == null)
            {
                dictionaries = new Dictionary<string, Dictionary>();
                foreach (string dictName in DictNames)
                {
                    Dictionary dict = Dao.LoadDictionary(dictName);
                    dictionaries.Add(dictName, dict);
                }
            }
        }

        public int GetCodeByLabel(string dictionaryName, string label)
        {
            Validate.NotBlank(label, "Label is illegal: blank");
            Dictionary dict = GetDictionary(dictionaryName);
            if (dict.ContainsValue(label))
            {
                Dictionary.Enumerator enumerator = dict.GetEnumerator();
                while (enumerator.MoveNext()) 
                {
                    if (enumerator.Current.Value == label)
                    {
                        return enumerator.Current.Key;
                    }
                }
                throw new ApplicationException("No such label in dictionary: " + label);
            }
            else
            {
                throw new ApplicationException("No such label in dictionary: " + label);
            }
        }

        public string GetLabelByCode(string dictionaryName, int code)
        {
            Dictionary dict = GetDictionary(dictionaryName);
            if (dict.ContainsKey(code))
            {
                return dict[code];
            }
            else
            {
                throw new ApplicationException("No such code in dictionary: " + code);
            }
        }

        protected Dictionary GetDictionary(string dictName)
        {
            Validate.NotBlank(dictName, "Dictionary name is illegal: blank");
            if (dictionaries.ContainsKey(dictName))
            {
                return dictionaries[dictName];
            }
            else
            {
                throw new ApplicationException("No such dictionary: " + dictName);
            }
        }
    }
}
